//
//  body.cpp
//  template4
//
//  Created by Xiaochen Lian on 5/15/12.
//  Copyright (c) 2012 University of California, Los Angeles. All rights reserved.
//

#include "body.h"
#include "limb.h"

CBody::CBody(vec3 scale, vec4 pos) 
{
    m_type = BODY;
    m_scale = scale;
    set_pos(pos);
}

CBody::~CBody()
{
}

inline void CBody::set_material(const lighting_struct &material)
{
    m_material = material;
}

void CBody::build_model()
{
    m_tfm = Translate(m_model_pos);
    m_scale_mat = Scale(m_scale);
    
    const GLfloat shoulder_length = 3.0f;
    const GLfloat shoulder_loc = 0.5, tail_loc = 0.75f;
    
    m_material.ambient = color4( 0.8f, 0.8f, 0.8f, 1.0f );
    m_material.diffuse = color4( 0.8f, 0.8f, 0.8f, 1.0f );
    m_material.specular = color4( 0.1f, 0.1f, 0.1f, 1.0f );
    m_material.shininess = 10.0f;
    
    GLfloat x = sqrt(1 - shoulder_loc*shoulder_loc) * m_scale[0];
    GLfloat z = m_scale[2] * shoulder_loc;
    
    vec4 pos = vec4(x, 0.0f, z, 0.0f) + vec4(shoulder_length/2, 0.0f, 0.0f, 0.0f);
    CShoulder *rshoulder = new CShoulder(pos, shoulder_length);
    m_children.push_back(rshoulder);
    
    pos = vec4(-x, 0.0f, z, 0.0f) + vec4(-shoulder_length/2, 0.0f, 0.0f, 0.0f);
    CShoulder *lshoulder = new CShoulder(pos, -shoulder_length);
    m_children.push_back(lshoulder);

    x = sqrt(1 - tail_loc*tail_loc) * m_scale[0];
    z = m_scale[2] * tail_loc;
    //        CTail *tail = new CTail(2*x, 5);
    //        tail->set_pos(point4(-x, 0.0, z, 1.0));
    //        m_children.push_back(tail);
    //        
    for (int i = 0; i < m_children.size(); ++i)
        m_children[i]->build_model();
}


void CBody::draw(const mat4 &tfm_parent)
{
    // set shader variables
    glUniform4fv(uAmbient, 1, g_env_lighting.ambient * m_material.ambient);
    glUniform4fv(uDiffuse, 1, g_env_lighting.diffuse.x * m_material.diffuse);
    glUniform4fv(uSpecular, 1, g_env_lighting.specular * m_material.specular);
    glUniform1f(uShininess, g_env_lighting.shininess * m_material.shininess);
    // draw objects
    //        glBindVertexArray( m_shape_data.vao );
    //        for (int i = 0; i < m_children.size(); ++i)
    //            m_children[i]->draw(light_pos, env_lighting, pMc, cMw, tfm_parent*m_tfm);
    drawEllips(tfm_parent*m_tfm*m_scale_mat);
    for (int i = 0; i < m_children.size(); ++i)
        m_children[i]->draw(tfm_parent*m_tfm);
}

